package com.ruoyi.order.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public class StatisticsWebSocketHandler extends TextWebSocketHandler {
    private static final Logger logger = LoggerFactory.getLogger(StatisticsWebSocketHandler.class);
    private static final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
        System.out.println("WebSocket连接建立，sessionId={}" + session.getId());
//        logger.info("WebSocket连接建立，sessionId={}", session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
        System.out.println("WebSocket连接关闭，sessionId={}，状态={}" + session.getId() + status);
//        logger.info("WebSocket连接关闭，sessionId={}，状态={}", session.getId(), status);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println("收到前端消息" + session.getId() + message.getPayload());
//        logger.info("收到前端消息，sessionId={}，内容={}", session.getId(), message.getPayload());
        // 可根据需要处理前端消息
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        System.out.println("WebSocket传输异常，sessionId={}" + session.getId() + exception);
//        logger.error("WebSocket传输异常，sessionId={}", session.getId(), exception);
    }

    // 推送数据给所有连接的客户端
    public static void broadcast(Object data) {
        String json;
        try {
            json = objectMapper.writeValueAsString(data);
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(json));
                    System.out.println("推送数据到前端，sessionId={}，内容={}" + session.getId() + json);
//                    logger.info("推送数据到前端，sessionId={}，内容={}", session.getId(), json);
                }
            }
        } catch (Exception e) {
            System.out.println("推送数据到前端失败" + e);
//            logger.error("推送数据到前端失败", e);
        }
    }
}
